import message from '@/utils/message';
import secret from './secret';
/**
 * 过滤对象中为空的属性
 * @param obj
 * @returns {*}
 */
export function filterObj (obj:{[propName:string]:any}) 
{
    if (!(typeof obj === 'object')) 
    {
        return;
    }

    for ( let key in obj) 
    {
        if (Object.prototype.hasOwnProperty.call(obj, key) && (obj[key] === null || obj[key] === undefined || obj[key] === '')) 
        {
            delete obj[key];
        }
    }
    return obj;
}

/**
 * 时间格式化
 * @param value
 * @param fmt
 * @returns {*}
 */
export function formatDate (value, fmt) 
{
    let regPos = /^\d+(\.\d+)?$/;
    if (regPos.test(value))
    {
        // 如果是数字
        let getDate = new Date(value);
        let o = {
            'M+': getDate.getMonth() + 1,
            'd+': getDate.getDate(),
            'h+': getDate.getHours(),
            'm+': getDate.getMinutes(),
            's+': getDate.getSeconds(),
            'q+': Math.floor((getDate.getMonth() + 3) / 3),
            'S': getDate.getMilliseconds()
        };
        if (/(y+)/.test(fmt)) 
        {
            fmt = fmt.replace(RegExp.$1, (getDate.getFullYear() + '').substr(4 - RegExp.$1.length));
        }
        for (let k in o) 
        {
            if (new RegExp('(' + k + ')').test(fmt)) 
            {
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
            }
        }
        return fmt;
    }
    value = value.trim();
    return value.substr(0, fmt.length);
}


/**
 * 深度克隆对象、数组
 * @param obj 被克隆的对象
 * @return 克隆后的对象
 */
export function cloneObject (obj:{[propName:string]:any}) 
{
    return JSON.parse(JSON.stringify(obj));
}

/**
 * 随机生成数字
 *
 * 示例：生成长度为 12 的随机数：randomNumber(12)
 * 示例：生成 3~23 之间的随机数：randomNumber(3, 23)
 *
 * @param1 最小值 | 长度
 * @param2 最大值
 * @return int 生成后的数字
 */
export function randomNumber (min, max) 
{
    // 生成 最小值 到 最大值 区间的随机数
    const random = (min1, max1) => 
    {
        return Math.floor(Math.random() * (max1 - min1 + 1) + min1);
    };
    if (!max) 
    {
        // eslint-disable-next-line prefer-rest-params
        // let [length] = arguments;
        // 生成指定长度的随机数字，首位一定不是 0
        let nums = [...Array(min).keys()].map((i) => (i > 0 ? random(0, 9) : random(1, 9)));
        return parseInt(nums.join(''));
    }
    return random(min, max);
}

/**
 * 随机生成字符串
 * @param length 字符串的长度
 * @param chats 可选字符串区间（只会生成传入的字符串中的字符）
 * @return string 生成的字符串
 */
export function randomString (length, chats) 
{
    if (!length) length = 1;
    if (!chats) chats = '0123456789qwertyuioplkjhgfdsazxcvbnm';
    let str = '';
    for (let i = 0; i < length; i++) 
    {
        let num = randomNumber(0, chats.length - 1);
        str += chats[num];
    }
    return str;
}

/**
 * 随机生成uuid
 * @return string 生成的uuid
 */
export function randomUUID () 
{
    let chats = '0123456789abcdef';
    return randomString(32, chats);
}

/**
 * 随机生成ID
 * @returns string
 */
export function randomID (length)
{
    let date = new Date().getTime();
    return randomString(length, secret.Encrypt(date));
}

/**
 * 随机生成用户账号
 * @param length 长度
 * @param firstNum 首位数字
 * @returns number
 */
export function randomUsername (length, firstNum)
{
    const random = (min1, max1) => 
    {
        return Math.floor(Math.random() * (max1 - min1 + 1) + min1);
    };
    
    let nums = [...Array(length).keys()].map((i) => (i > 0 ? random(0, 9) : firstNum));
    return parseInt(nums.join(''));
}


/**
 * 下划线转驼峰
 * @param string
 * @returns {*}
 */
export function underLine2CamelCase (string)
{
    return string.replace( /_([a-z])/g, function ( all, letter ) 
    {
        return letter.toUpperCase();
    });
}

export function randomFoxId ()
{
    return Number(Math.random().toString().substr(3, 4) + Date.now()).toString(36);
}


export function formatTime (value:any) 
{
    // 通过时间戳转字符串或者获取时间字符串
    let date = value ? new Date(value) : new Date();
    let yy = date.getFullYear();
    let mm = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
    let dd = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    let hh = date.getHours() < 10 ? '0' +  date.getHours() : date.getHours();
    let mf = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
    let ss = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
    return yy + '-' + mm + '-' + dd + ' ' + hh + ':' + mf + ':' + ss;
}

export function formatWeek (value)
{
    let weeks = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    if (value === '7') return weeks[0];
    return weeks[value];
}

export function formatWeeks (value)
{
    let weeks = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
    if (value === '7') return weeks[0];
    return weeks[value];
}

// 转时间戳
export function formatTimeStamp (time:any):number
{    
    if (!time)
    {
        return 0;
    }
    let date = time.replace(/-/g, '/');
    let timestamp = new Date(date).getTime();
    return timestamp;
}

function isYestday (theDate:any)
{
    let date = new Date();    // 当前时间
    let today = new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime(); // 今天凌晨
    let yestday = new Date(today - 24 * 3600 * 1000).getTime();
    return theDate < today && yestday <= theDate;
}


function isYear (timeValue:any) 
{ 
    // 是否为今年
    const dateyear = new Date(timeValue).getFullYear();
    const toyear = new Date().getFullYear();
    if (dateyear === toyear) 
    {
        return true;
    }
    return false;
}

export function timeChange (timeValue:any) 
{
    let timeOld = formatTimeStamp(timeValue);
    let timeNew = new Date().getTime(); // 当前时间
    let timeDiffer = timeNew - timeOld; // 与当前时间误差
    let returnTime = '';
    if (timeDiffer <= 60000) 
    { // 一分钟内
        returnTime = '刚刚';
    } 
    else if (timeDiffer > 60000 && timeDiffer < 3600000) 
    { // 1小时内
        returnTime = Math.floor(timeDiffer / 60000) + '分钟前';
    } 
    else if (timeDiffer >= 3600000 && timeDiffer < 86400000 && isYestday(timeOld) === false) 
    { // 今日
        returnTime = timeValue.substr(11, 5);
    } 
    else if (timeDiffer > 3600000 && isYestday(timeOld) === true) 
    { // 昨天
        returnTime = '昨天' + timeValue.substr(11, 5);
    } 
    else if (timeDiffer > 86400000 && isYestday(timeOld) === false && isYear(timeOld) === true) 
    { // 今年
        returnTime = timeValue.substr(5, 11);
    } 
    else if (timeDiffer > 86400000 && isYestday(timeOld) === false && isYear(timeOld) === false) 
    { // 不属于今年
        returnTime = timeValue.substr(0, 10);
    }
    return returnTime;
}

export function copyText (text)
{
    if (text.trim() === '') return;
    let input = document.createElement('input');
    input.value = text;
    document.body.appendChild(input);
    input.select();
    document.execCommand('copy');
    message.success('复制成功');
    document.body.removeChild(input);
}

export function downloadIamge (imgsrc, name) 
{
    // 下载图片地址和图片名
    let image = new Image();
    // 解决跨域 Canvas 污染问题
    image.setAttribute('crossOrigin', 'anonymous');
    image.onload = function () 
    {
        const canvas = document.createElement('canvas');
        canvas.width = image.width;
        canvas.height = image.height;
        const context:any = canvas.getContext('2d');
        context.drawImage(image, 0, 0, image.width, image.height);
        const url = canvas.toDataURL('image/png'); // 得到图片的base64编码数据
        const a = document.createElement('a'); // 生成一个a元素
        const event = new MouseEvent('click'); // 创建一个单击事件
        a.download = name || 'photo'; // 设置图片名称
        a.href = url; // 将生成的URL设置为a.href属性
        a.dispatchEvent(event); // 触发a的单击事件
    };
    image.src = imgsrc;
}

export function downloadFile (url, name, callback1, callback2, callback3) 
{
    let xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'blob'; // 返回类型blob
    // 监听进度
    xhr.onprogress = function (e) 
    {
        if (e.lengthComputable) 
        {
            callback2(Number((e.loaded / e.total * 100).toFixed(0)));
        }
    };
    xhr.onload = function () 
    {
        if (xhr.readyState === 4 && xhr.status === 200) 
        {
            let blob = this.response;
            // 转换⼀个blob链接 转内存url
            let u = window.URL.createObjectURL(new Blob([blob]));
            let a = document.createElement('a');
            a.download = name;
            a.href = u;
            a.style.display = 'none';
            document.body.appendChild(a);
            a.click();
            a.remove();
            // 释放
            window.URL.revokeObjectURL(u);
            callback3();
            callback1(0);
        }
        else
        {
            message.error('下载失败,文件已失效');
            callback1(0);
        }
    };
    xhr.onerror = function ()
    {
        message.error('下载失败,文件已失效');
        callback1(0);
    };
    xhr.send();
}

export const isObject = (data) => Object.prototype.toString.call(data) === '[object Object]';
export const isArray = (data) => Object.prototype.toString.call(data) === '[object Array]';

// 备忘录的排序
export const noteSort = (data, order) => 
{
    const sortDefalut = () => 
    {
        // 默认排序
        for (let i = 0; i < data.length - 1; i++)
        {
            for (let j = 0; j < data.length - 1 - i; j++)
            {
                if (data[j].isTop === data[j + 1].isTop)
                {
                    if (formatTimeStamp(data[j].ut) < formatTimeStamp(data[j + 1].ut))
                    {
                        let temp = data[j];
                        data[j] = data[j + 1];
                        data[j + 1] = temp;
                    }
                }
                else if (data[j].isTop < data[j + 1].isTop)
                {
                    let temp = data[j];
                    data[j] = data[j + 1];
                    data[j + 1] = temp;
                }
            }
        }
        return data;
    };

    const sortOther = () => 
    {
        let key = '';
        if (order === 1 || order === 2) key = 'ct';
        else key = 'ut';
        for (let i = 0; i < data.length - 1; i++)
        {
            for (let j = 0; j < data.length - 1 - i; j++)
            {
                if (order === 1 || order === 3)
                {
                    // 创建时间 升序排序 从旧到新
                    if (formatTimeStamp(data[j][key]) > formatTimeStamp(data[j + 1][key]))
                    {
                        let temp = data[j];
                        data[j] = data[j + 1];
                        data[j + 1] = temp;
                    }
                }
                else
                {
                    // 创建时间 降序排序
                    if (formatTimeStamp(data[j][key]) < formatTimeStamp(data[j + 1][key]))
                    {
                        let temp = data[j];
                        data[j] = data[j + 1];
                        data[j + 1] = temp;
                    }
                }
            }
        }
        return data;
    };
    if (order === 0) return sortDefalut();
    return sortOther();
};

// 待办事项的排序
export const todoSort = (data) => 
{
    const sortDefalut = () => 
    {
        // 默认排序
        for (let i = 0; i < data.length - 1; i++)
        {
            for (let j = 0; j < data.length - 1 - i; j++)
            {
                if (data[j].isFinish === data[j + 1].isFinish)
                {
                    if (formatTimeStamp(data[j].ut) < formatTimeStamp(data[j + 1].ut))
                    {
                        let temp = data[j];
                        data[j] = data[j + 1];
                        data[j + 1] = temp;
                    }
                }
                else if (data[j].isFinish > data[j + 1].isFinish)
                {
                    let temp = data[j];
                    data[j] = data[j + 1];
                    data[j + 1] = temp;
                }
            }
        }
        return data;
    };
    return sortDefalut();
};


export function dataURLtoBlob (dataurl) 
{
    let arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while (n--) 
    {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
}

// Blob对象转Base64
export function blobToDataURL (blob, callback) 
{ 
    let a = new FileReader();
    a.onload = function (e:any) 
    { 
        callback(e.target.result); 
    };
    a.readAsDataURL(blob);
}

// 转 (url)
export function getObjectURL (file) 
{ 
    let url = null as any;
    if (window.URL !== undefined) 
    { // mozilla(firefox)
        url = window.URL.createObjectURL(file);
    } 
    else if (window.webkitURL !== undefined) 
    { // webkit or chrome
        url = window.webkitURL.createObjectURL(file);
    }
    return url;
}

// base64转blob
export function dataURItoBlob (base64Data) 
{  
    let byteString;
    let mimeString;
    if (base64Data.split(',')[0].indexOf('base64') >= 0) 
    {
        byteString = atob(base64Data.split(',')[1]);
    } 
    else 
    {
        byteString = unescape(base64Data.split(',')[1]);
        mimeString = base64Data.split(',')[0].split(':')[1].split(';')[0];
    }
    let ia = new Uint8Array(byteString.length);
    for (let i = 0; i < byteString.length; i++) 
    {
        ia[i] = byteString.charCodeAt(i);
    }
    return new Blob([ia], {type: mimeString});
}


// 识别链接
export function tellUrl (text?:string)
{
    const URL_REG = 
    // eslint-disable-next-line no-useless-escape
    /(((https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)/;
    if (!text) return text;
    const reg = new RegExp(URL_REG, 'gi');
    return text.replaceAll(reg, "<a href='$1' target='_blank'>$1</a>");
}